﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace Doo.WebUI.SiteBuilder
{
    public abstract class BuilderPage<TWidgetProvider> : DooPage
        where TWidgetProvider : WidgetProvider, new()
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            #region 在此创建并加载控件

            ControlCollection cc = GetWidgetContainer();
            var wctls = GetWidgetControls();
            foreach (Control wc in wctls)
            {
                cc.Add(wc);
            }
            #endregion
        }

        public virtual Control[] GetWidgetControls()
        {
            TWidgetProvider wp = new TWidgetProvider();
            wp.OwnPage = this;
            var config = wp.GetWidgetConfig("root");
            PlaceHolder ph_eps = new PlaceHolder();//container of property editors
            HashSet<Type> wtpes = new HashSet<Type>();
            //开始创建控件
            wp.ControlCreated = delegate(Control newctl)
            {
                //create property editor
                Type wt = newctl.GetType();
                if (!wtpes.Contains(wt))
                {
                    wtpes.Add(wt);
                    PropertyEditor.EditorPanel ep = PropertyEditor.EditorHelper.CreateEditorPanel(wt, wt.FullName);
                    ph_eps.Controls.Add(ep);
                }
                return new WidgetConfigControl(newctl);
            };
            var ctl = wp.CreateWidgetControl(config);

            return new Control[] { ctl, ph_eps };
        }


        public abstract ControlCollection GetWidgetContainer();
    }
}

namespace Doo
{
    public static class DooHelper
    {
        public static bool IsChildOf(this Type t, Type basetype)
        {
            do
            {
                if (t.BaseType == basetype) return true;
                t = t.BaseType;
            }
            while (t != null && t.BaseType != null);
            return false;
        }
    }
}